<template>
	<view class="container" @click="closeAllDropdowns">
		<!-- 顶部搜索和筛选区域 -->
		<view class="search-filter-container">
			<view class="search-box">
				<uni-icons type="search" size="20" color="#8898AA"></uni-icons>
				<input class="search-input" v-model="searchParams.name" placeholder="请输入学生姓名" @confirm="loadStudents" />
				<uni-icons v-if="searchParams.name" type="clear" size="18" color="#8898AA"
					@click="clearSearch"></uni-icons>
			</view>

			<view class="filter-options">
				<view class="filter-item-container">
					<view class="dropdown-select" @click.stop="toggleDropdown('grade')">
						<text class="dropdown-text">{{ gradeOptions[gradeIndex] || '年级' }}</text>
						<view class="dropdown-icon">
							<uni-icons :type="gradeDropdownOpen ? 'top' : 'bottom'" size="14" color="#8898AA"></uni-icons>
						</view>
					</view>
					<view class="dropdown-menu" v-if="gradeDropdownOpen">
						<view class="dropdown-item" :class="{'dropdown-item-active': index === gradeIndex}" 
							v-for="(item, index) in gradeOptions" :key="index" @click.stop="selectGrade(index)">
							<text>{{ item }}</text>
						</view>
					</view>
				</view>

				<view class="filter-item-container">
					<view class="dropdown-select" @click.stop="toggleDropdown('class')">
						<text class="dropdown-text">{{ classOptions[classIndex] || '班级' }}</text>
						<view class="dropdown-icon">
							<uni-icons :type="classDropdownOpen ? 'top' : 'bottom'" size="14" color="#8898AA"></uni-icons>
						</view>
					</view>
					<view class="dropdown-menu" v-if="classDropdownOpen">
						<view class="dropdown-item" :class="{'dropdown-item-active': index === classIndex}" 
							v-for="(item, index) in classOptions" :key="index" @click.stop="selectClass(index)">
							<text>{{ item }}</text>
						</view>
					</view>
				</view>

				<view class="filter-item-container">
					<view class="dropdown-select" @click.stop="toggleDropdown('status')">
						<text class="dropdown-text">{{ statusOptions[statusIndex] || '状态' }}</text>
						<view class="dropdown-icon">
							<uni-icons :type="statusDropdownOpen ? 'top' : 'bottom'" size="14" color="#8898AA"></uni-icons>
						</view>
					</view>
					<view class="dropdown-menu" v-if="statusDropdownOpen">
						<view class="dropdown-item" :class="{'dropdown-item-active': index === statusIndex}" 
							v-for="(item, index) in statusOptions" :key="index" @click.stop="selectStatus(index)">
							<text>{{ item }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 学生列表 -->
		<scroll-view scroll-y class="student-list" @scrolltolower="onLoadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh" :show-scrollbar="studentList.length > 0">
			<view v-if="studentList.length > 0" class="student-item" v-for="(student, index) in studentList"
				:key="student._id" @click="navigateToDetail(student._id)">
				<view class="student-info">
					<view class="student-top-row">
						<view class="student-left">
							<text class="student-name">{{ student.name }}</text>
							<text
								:class="['student-status', {'status-active': student.status === 1, 'status-inactive': student.status === 0}]">
								{{ student.status === 1 ? '在读' : '退学' }}
							</text>
						</view>
						<view class="student-grade-class">
							<text class="grade-tag">{{ student.grade }}</text>
							<text class="class-tag">{{ student.class }}班</text>
						</view>
					</view>
					<view class="student-parent">
						<text class="parent-info">家长：{{ student.parent_name }}</text>
						<text class="parent-info">电话：{{ student.parent_phone }}</text>
					</view>
				</view>
				<view class="student-actions">
					<uni-icons type="right" size="20" color="#8898AA"></uni-icons>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="studentList.length === 0 && !loading" class="empty-state">
				<image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无学生数据</text>
			</view>

			<!-- 加载中状态 -->
			<view v-if="loading && !refreshing" class="loading-state">
				<uni-load-more status="loading" :contentText="loadMoreText"></uni-load-more>
			</view>

			<!-- 加载更多 -->
			<uni-load-more v-if="studentList.length > 0 && !loading" :status="loadMoreStatus"
				:contentText="loadMoreText"></uni-load-more>
		</scroll-view>

		<!-- 添加按钮 -->
		<view class="add-button" @click="navigateToAdd">
			<uni-icons type="plus" size="28" color="#FFFFFF"></uni-icons>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';
	import {
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import PinyinMatch from 'pinyin-match';

	// 状态定义
	const studentList = ref([]);
	const total = ref(0);
	const loading = ref(false);
	const refreshing = ref(false);
	// 存储完整学生列表以供前端过滤
	const allStudents = ref([]);

	// 下拉框状态
	const gradeDropdownOpen = ref(false);
	const classDropdownOpen = ref(false);
	const statusDropdownOpen = ref(false);

	const searchParams = reactive({
		name: '',
		grade: '',
		class: '',
		status: '',
		page: 1,
		pageSize: 10
	});

	// 筛选选项
	const gradeOptions = ref(['全部年级']);
	const classOptions = ref(['全部班级']);
	const statusOptions = ref(['全部状态', '在读', '退学']);
	const gradeIndex = ref(0);
	const classIndex = ref(0);
	const statusIndex = ref(0);

	// 加载更多状态
	const loadMoreStatus = computed(() => {
		if (studentList.value.length >= total.value && studentList.value.length > 0) {
			return 'noMore';
		}
		return 'more';
	});

	const loadMoreText = {
		contentdown: '上拉加载更多',
		contentrefresh: '加载中...',
		contentnomore: '没有更多数据了'
	};

	// 加载学生数据
	async function loadStudents(resetPage = true) {
		if (resetPage) {
			searchParams.page = 1;
			studentList.value = [];
		}

		loading.value = true;

		try {
			const studentCloud = uniCloud.importObject('student');
			
			// 如果有搜索词，尝试在前端进行拼音匹配
			if (searchParams.name && allStudents.value.length > 0) {
				console.log('进行前端拼音搜索过滤');
				
				// 过滤出匹配的学生（包括汉字和拼音匹配）
				const filteredList = allStudents.value.filter(student => {
					// 直接包含搜索词
					if (student.name.toLowerCase().includes(searchParams.name.toLowerCase())) {
						return true;
					}
					// 拼音匹配
					return PinyinMatch.match(student.name, searchParams.name);
				});
				
				// 应用其他过滤条件
				let matchedStudents = filteredList;
				
				if (searchParams.grade) {
					matchedStudents = matchedStudents.filter(s => s.grade === searchParams.grade);
				}
				
				if (searchParams.class) {
					matchedStudents = matchedStudents.filter(s => s.class === searchParams.class);
				}
				
				if (searchParams.status !== undefined && searchParams.status !== '') {
					matchedStudents = matchedStudents.filter(s => s.status === Number(searchParams.status));
				}
				
				// 按学生姓名字母顺序排序
				matchedStudents.sort((a, b) => {
					return a.name.localeCompare(b.name, 'zh-CN');
				});
				
				// 更新学生列表和总数（添加前端分页）
				const start = (searchParams.page - 1) * searchParams.pageSize;
				const end = start + searchParams.pageSize;
				
				if (resetPage) {
					studentList.value = matchedStudents.slice(start, end);
				} else {
					studentList.value = [...studentList.value, ...matchedStudents.slice(start, end)];
				}
				
				total.value = matchedStudents.length;
				
				loading.value = false;
				refreshing.value = false;
				return;
			}
			
			// 否则进行正常的后端请求
			const result = await studentCloud.getStudentList(searchParams);
			
			let studentData = [];
			if (resetPage) {
				studentData = result.list;
			} else {
				studentData = [...studentList.value, ...result.list];
			}
			
			// 按学生姓名字母顺序排序
			studentData.sort((a, b) => {
				return a.name.localeCompare(b.name, 'zh-CN');
			});
			
			// 更新学生列表
			studentList.value = studentData;
			total.value = result.total;
			searchParams.page = result.page;
		} catch (error) {
			console.error('加载学生数据失败:', error);
			uni.showToast({
				title: '加载学生数据失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
			refreshing.value = false;
		}
	}

	// 加载更多数据
	function onLoadMore() {
		if (loading.value || studentList.value.length >= total.value) {
			return;
		}

		searchParams.page += 1;
		loadStudents(false);
	}

	// 下拉刷新
	function onRefresh() {
		refreshing.value = true;
		loadStudents();
	}

	// 清除搜索
	function clearSearch() {
		searchParams.name = '';
		loadStudents();
	}

	// 年级筛选变化
	function onGradeChange(e) {
		gradeIndex.value = e.detail.value;
		if (gradeIndex.value === 0) {
			searchParams.grade = '';
		} else {
			searchParams.grade = gradeOptions.value[gradeIndex.value];
		}
		loadStudents();
	}

	// 班级筛选变化
	function onClassChange(e) {
		classIndex.value = e.detail.value;
		if (classIndex.value === 0) {
			searchParams.class = '';
		} else {
			searchParams.class = classOptions.value[classIndex.value];
		}
		loadStudents();
	}

	// 状态筛选变化
	function onStatusChange(e) {
		statusIndex.value = e.detail.value;
		if (statusIndex.value === 0) {
			searchParams.status = '';
		} else if (statusIndex.value === 1) {
			searchParams.status = 1; // 在读
		} else if (statusIndex.value === 2) {
			searchParams.status = 0; // 退学
		}
		loadStudents();
	}

	// 下拉框控制
	function toggleDropdown(type) {
		if (type === 'grade') {
			gradeDropdownOpen.value = !gradeDropdownOpen.value;
			classDropdownOpen.value = false;
			statusDropdownOpen.value = false;
		} else if (type === 'class') {
			gradeDropdownOpen.value = false;
			classDropdownOpen.value = !classDropdownOpen.value;
			statusDropdownOpen.value = false;
		} else if (type === 'status') {
			gradeDropdownOpen.value = false;
			classDropdownOpen.value = false;
			statusDropdownOpen.value = !statusDropdownOpen.value;
		}
	}

	// 选择年级
	function selectGrade(index) {
		gradeIndex.value = index;
		if (index === 0) {
			searchParams.grade = '';
		} else {
			searchParams.grade = gradeOptions.value[index];
		}
		gradeDropdownOpen.value = false;
		loadStudents();
	}

	// 选择班级
	function selectClass(index) {
		classIndex.value = index;
		if (index === 0) {
			searchParams.class = '';
		} else {
			searchParams.class = classOptions.value[index];
		}
		classDropdownOpen.value = false;
		loadStudents();
	}

	// 选择状态
	function selectStatus(index) {
		statusIndex.value = index;
		if (index === 0) {
			searchParams.status = '';
		} else if (index === 1) {
			searchParams.status = 1; // 在读
		} else if (index === 2) {
			searchParams.status = 0; // 退学
		}
		statusDropdownOpen.value = false;
		loadStudents();
	}

	// 导航到学生详情页
	function navigateToDetail(id) {
		uni.navigateTo({
			url: `/pages/student/detail?id=${id}`
		});
	}

	// 导航到添加学生页面
	function navigateToAdd() {
		uni.navigateTo({
			url: '/pages/student/add'
		});
	}

	// 关闭所有下拉框
	function closeAllDropdowns() {
		gradeDropdownOpen.value = false;
		classDropdownOpen.value = false;
		statusDropdownOpen.value = false;
	}

	// 初始化时加载所有学生数据用于前端搜索
	async function loadAllStudentsForSearch() {
		try {
			const studentCloud = uniCloud.importObject('student');
			const result = await studentCloud.debugGetAllStudents();
			
			if (result && result.data) {
				allStudents.value = result.data;
				console.log('预加载所有学生数据成功，共', allStudents.value.length, '条记录');
			}
		} catch (error) {
			console.error('预加载学生数据失败:', error);
		}
	}

	// 初始化
	onMounted(async () => {
		// 调试代码：直接获取所有学生数据检查
		try {
			const studentCloud = uniCloud.importObject('student');
			const debugResult = await studentCloud.debugGetAllStudents();
			console.log('调试数据库检查结果:', debugResult);

			if (debugResult.count > 0) {
				console.log('数据库中共有' + debugResult.count + '条学生记录');
				console.log('第一条记录:', debugResult.data[0]);
				
				// 保存数据用于前端搜索
				allStudents.value = debugResult.data;
			} else {
				console.log('数据库中没有任何学生记录');
			}
		} catch (error) {
			console.error('调试查询失败:', error);
		}

		// 正常初始化
		await loadFilterOptions();
		loadStudents();
	});

	// 加载筛选选项
	async function loadFilterOptions() {
		try {
			const studentCloud = uniCloud.importObject('student');
			const {
				grades,
				classes
			} = await studentCloud.getGradeAndClassList();

			if (grades && grades.length > 0) {
				gradeOptions.value = ['全部年级', ...grades];
			}

			if (classes && classes.length > 0) {
				classOptions.value = ['全部班级', ...classes];
			}
		} catch (error) {
			console.error('加载筛选选项失败:', error);
			uni.showToast({
				title: '加载筛选选项失败',
				icon: 'none'
			});
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F8F9FC;
		position: relative;
	}

	.search-filter-container {
		background: linear-gradient(to bottom, #FFFFFF, #FAFBFC);
		padding: 24px 24px 20px;
		border-bottom: 1px solid rgba(233, 236, 239, 0.8);
		box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
		z-index: 10;
		position: relative;
		transition: all 0.3s ease;
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #F8F9FC;
		border-radius: 12px;
		padding: 8px 16px;
		margin-bottom: 16px;
		border: 1.5px solid #E9ECEF;
		transition: all 0.3s ease;
		box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.01);
	}

	.search-box:focus-within {
		border-color: #0A6CFF;
		box-shadow: 0 0 0 3px rgba(10, 108, 255, 0.15), inset 0 2px 4px rgba(0, 0, 0, 0.01);
	}

	.search-input {
		flex: 1;
		height: 20px;
		line-height: 20px;
		margin: 0 8px;
		font-size: 15px;
		color: #172B4D;
	}

	.filter-options {
		display: flex;
		justify-content: space-between;
		margin-top: 12px;
		width: 100%;
	}

	.filter-item-container {
		position: relative;
		flex: 1;
		margin: 0 4px;
	}
	
	.filter-item-container:first-child {
		margin-left: 0;
	}
	
	.filter-item-container:last-child {
		margin-right: 0;
	}

	.dropdown-select {
		display: flex;
		align-items: center;
		font-size: 12px;
		color: #8898AA;
		padding: 8px 10px;
		background-color: #F8F9FC;
		border-radius: 12px;
		transition: all 0.3s ease;
		border: 1px solid #E9ECEF;
		width: 100%;
		justify-content: space-between;
		box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.01);
		height: 36px;
		box-sizing: border-box;
	}
	
	.dropdown-text {
		font-weight: 500;
		font-size: 13px;
		flex: 1;
		overflow: visible;
		white-space: nowrap;
	}
	
	.dropdown-icon {
		width: 14px;
		flex-shrink: 0;
		margin-left: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.dropdown-menu {
		position: absolute;
		top: calc(100% + 4px);
		left: 0;
		width: auto; 
		min-width: 100%;
		background-color: #FFFFFF;
		border-radius: 12px;
		box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
		padding: 6px 0;
		z-index: 100;
		border: 1px solid rgba(233, 236, 239, 0.8);
		max-height: 240px;
		overflow-y: auto;
	}

	.dropdown-item {
		padding: 8px 12px;
		font-size: 13px;
		color: #8898AA;
		transition: all 0.2s ease;
		border-radius: 6px;
		margin: 2px 6px;
		white-space: nowrap;
	}

	.dropdown-item:active {
		background-color: #F0F4F8;
		color: #0A6CFF;
	}

	.dropdown-item-active {
		background-color: rgba(10, 108, 255, 0.08);
		color: #0A6CFF;
		font-weight: 500;
	}
	
	.dropdown-select:active {
		background-color: #F0F4F8;
		transform: scale(0.99);
		border-color: rgba(10, 108, 255, 0.3);
	}

	.student-list {
		flex: 1;
		padding: 20px 12px 100px;
		box-sizing: border-box;
		width: 100%;
		overflow-x: hidden;
	}

	.student-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: linear-gradient(to bottom, #FFFFFF, #FAFBFC);
		border-radius: 16px;
		padding: 22px 16px 22px 20px;
		margin-bottom: 20px;
		box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.02);
		transition: all 0.3s cubic-bezier(0.2, 0, 0, 1);
		border: 1px solid rgba(233, 236, 239, 0.7);
		position: relative;
		overflow: hidden;
	}

	.student-item::before {
		content: '';
		position: absolute;
		left: 0;
		top: 0;
		height: 100%;
		width: 4px;
		background: linear-gradient(to bottom, #0A6CFF, #0057E3);
		opacity: 0;
		transition: opacity 0.3s ease;
		border-top-left-radius: 16px;
		border-bottom-left-radius: 16px;
	}

	.student-item:active {
		transform: scale(0.98) translateX(2px);
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
		background: linear-gradient(to bottom, #FAFBFC, #FFFFFF);
	}

	.student-item:active::before {
		opacity: 1;
	}

	.student-info {
		flex: 1;
		min-width: 0;
	}

	.student-top-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 12px;
	}

	.student-left {
		display: flex;
		align-items: center;
		min-width: 0;
		margin-right: 10px;
	}

	.student-name {
		font-size: 17px;
		font-weight: 600;
		color: #172B4D;
		margin-right: 10px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		letter-spacing: -0.2px;
		max-width: 120px;
	}

	.student-status {
		font-size: 12px;
		padding: 3px 8px;
		border-radius: 20px;
		white-space: nowrap;
		font-weight: 500;
		display: flex;
		align-items: center;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
	}

	.status-active {
		background-color: rgba(45, 206, 137, 0.08);
		color: #2DCE89;
		border: 1px solid rgba(45, 206, 137, 0.15);
	}

	.status-inactive {
		background-color: rgba(245, 54, 92, 0.08);
		color: #F5365C;
		border: 1px solid rgba(245, 54, 92, 0.15);
	}

	.student-grade-class {
		display: flex;
		align-items: center;
		white-space: nowrap;
	}
	
	.grade-tag {
		font-size: 13px;
		color: #0A6CFF;
		background-color: rgba(10, 108, 255, 0.08);
		padding: 2px 8px;
		border-radius: 10px;
		margin-right: 5px;
		border: 1px solid rgba(10, 108, 255, 0.15);
		font-weight: 500;
	}
	
	.class-tag {
		font-size: 13px;
		color: #9B59B6;
		background-color: rgba(155, 89, 182, 0.08);
		padding: 2px 8px;
		border-radius: 10px;
		border: 1px solid rgba(155, 89, 182, 0.15);
		font-weight: 500;
	}

	.student-parent {
		display: flex;
		flex-direction: row;
		font-size: 14px;
		color: #8898AA;
		letter-spacing: 0.1px;
		flex-wrap: wrap;
	}

	.parent-info {
		margin-right: 12px;
	}

	.student-actions {
		height: 100%;
		display: flex;
		align-items: center;
		padding-left: 12px;
		opacity: 0.7;
		transition: opacity 0.3s ease;
		flex-shrink: 0;
	}

	.student-item:active .student-actions {
		opacity: 1;
	}

	.add-button {
		position: fixed;
		right: 24px;
		bottom: 80px;
		width: 60px;
		height: 60px;
		border-radius: 30px;
		background: linear-gradient(135deg, #0A6CFF, #0057E3);
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 10px 20px rgba(10, 108, 255, 0.35), 0 4px 8px rgba(10, 108, 255, 0.2);
		transition: all 0.3s cubic-bezier(0.2, 0, 0, 1);
		z-index: 100;
		border: 1px solid rgba(255, 255, 255, 0.15);
		overflow: hidden;
	}

	.add-button::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: radial-gradient(circle at center, rgba(255, 255, 255, 0.2), transparent 70%);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.add-button:active {
		transform: scale(0.92) translateY(3px);
		box-shadow: 0 4px 10px rgba(10, 108, 255, 0.2);
	}

	.add-button:active::after {
		opacity: 1;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 72px 20px;
		background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), rgba(250, 251, 252, 0.9));
		border-radius: 16px;
		margin: 36px 8px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.04), 0 2px 8px rgba(0, 0, 0, 0.02);
		border: 1px solid rgba(233, 236, 239, 0.7);
		position: relative;
		overflow: hidden;
		width: auto;
		max-width: calc(100% - 16px);
		height: auto;
	}

	.empty-state::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 4px;
		background: linear-gradient(to right, rgba(10, 108, 255, 0.5), rgba(0, 87, 227, 0.5));
		opacity: 0.5;
	}

	.empty-image {
		width: 120px;
		height: 120px;
		margin-bottom: 24px;
		opacity: 0.4;
		filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.05));
		transition: all 0.3s ease;
	}

	.empty-text {
		font-size: 15px;
		color: #8898AA;
		letter-spacing: -0.1px;
		font-weight: 500;
		text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
		text-align: center;
		padding: 0 10px;
		white-space: nowrap;
		max-width: 90%;
	}

	.loading-state {
		padding: 36px 0;
	}

	/* 重写uni组件样式 */
	:deep(.uni-load-more__text) {
		font-size: 14px;
		color: #8898AA;
		font-weight: 500;
		letter-spacing: 0.2px;
	}

	:deep(.uni-load-more__img) {
		width: 32px;
		height: 32px;
	}

	:deep(.uni-load-more__img > view) {
		border-color: #0A6CFF #E9ECEF #E9ECEF #E9ECEF;
	}
</style>